<?php
/**
 * Short description for file
 *
 * Long description for file (if any)...
 *
 * LICENSE: LGPL
 *
 * @category   Sabai
 * @package    Sabai_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2006 myWeb Japan (http://www.myweb.ne.jp/)
 * @license    http://opensource.org/licenses/lgpl-license.php GNU LGPL
 * @version    CVS: $Id: SelectEntities.php 196 2008-03-01 16:01:41Z mikhail.miguel $
 * @link
 * @since      File available since Release 0.1.1
*/

require_once 'Sabai/Form/Element/Select.php';

/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 * @category   Sabai
 * @package    Sabai_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2006 myWeb Japan (http://www.myweb.ne.jp/)
 * @author     Kazumi Ono <onokazu@gmail.com>
 * @license    http://opensource.org/licenses/lgpl-license.php GNU LGPL
 * @version    CVS: $Id: SelectEntities.php 196 2008-03-01 16:01:41Z mikhail.miguel $
 * @link
 * @since      Class available since Release 0.1.1
 */
class Sabai_Form_Element_SelectEntities extends Sabai_Form_Element_Select
{
    var $_model;
    var $_entityName;
    var $_html;

    function Sabai_Form_Element_SelectEntities(&$model, $entityName, $name)
    {
        parent::Sabai_Form_Element_Select(SABAI_FORM_TYPE_SELECTDROPDOWN, $name);
        $this->_model =& $model;
        $this->_entityName = $entityName;
    }

    function onView()
    {
        $repository =& $this->_model->getRepository($this->_entityName);
        //$pages =& $repository->paginateAll($this->_perpage, $this->_sort, $this->_order);
        //$page =& $pages->getValidPage($this->_currentPage);
        $total = $repository->countAll();;
        $perpage = 100;
        $pages =& $repository->paginateAll($perpage);
        $page =& $pages->getValidPage(1);
        $options =& $page->getEntities();
        $options->rewind();
        $selected_value = $this->getValue();
        settype($selected_value, 'array');
        $source_option_html = $target_option_html = array();
        while ($option =& $options->getNext()) {
            $value = $option->getId();
            $text = $option->getLabel();
            if (in_array($value, $selected_value)) {
                $target_option_html[] = sprintf('<option value="%s" selected="selected">%s</option>', h($value), h($text));
            } else {
                $source_option_html[] = sprintf('<option value="%s">%s</option>', h($value), h($text));
            }
        }
        $this->_html = $this->_getHTML($total, $perpage, implode("\n", $source_option_html), implode("\n", $target_option_html));
    }

    function getHTML($attr)
    {
        return $this->_html;
    }

    function _getHTML($total, $perpage, $srcOptionHTML, $targetOptionHTML)
    {
        $src = sprintf('select_%s_source', $this->getName());
        $target = sprintf('select_%s_target', $this->getName());
        $button_src = sprintf('button_%s_source', $this->getName());
        $button_target = sprintf('button_%s_target', $this->getName());
        $button_more = sprintf('button_%s_more', $this->getName());
        $html[] = sprintf('<div style="float:left;"><select id="%s" size="10" multiple="multiple">%s</select></div>', $src, $srcOptionHTML);
        $html[] = sprintf('<div style="float:left;"><input id="%s" type="button" value="%s" /><br /><input id="%s" type="button" value="%s" /></div>', $button_target, '-->', $button_src, '<--');
        $html[] = sprintf('<div style="float:left;"><select id="%s" name="%s[]" size="10" multiple="multiple">%s</select></div>', $target, $this->getName(), $targetOptionHTML);
        $html[] = sprintf('<div style="clear:left;"><input type="button" value="%s" id="%s" /></div>', '+', $button_more);
        $html[] = $this->_getHTMLforJS($src, $target, $button_src, $button_target, $button_more, $total, $perpage);
        return implode("\n", $html);
    }

    function _getHTMLforJS($src, $target, $button_src, $button_target, $button_more, $total, $perpage)
    {
        static $loaded = false;
        ob_start();
?>
<script type="text/javascript">
<?php
        if (!$loaded) {
?>
var Sabai_Form_Element_SelectEntities_Updater = Class.create();
Object.extend(Sabai_Form_Element_SelectEntities_Updater.prototype, {
    initialize: function(src, target, total, perpage)
    {
        this.src = src;
        this.target = target;
        this.total = total;
        this.perpage = perpage;
        this.currentpage = 1;
    },

    targetToSrc: function()
    {
        for (var i = 0; i < this.target.options.length; i++) {
            if (this.target.options[i].selected) {
                this.src.appendChild(this.target.options[i]);
                i--;
            } else {
                this.target.options[i].selected = true;
            }
        }
    },

    srcToTarget: function()
    {
        for (var i = 0; i < this.target.options.length; i++) {
            this.target.options[i].selected = true;
        }
        for (var i = 0; i < this.src.options.length; i++) {
            if (this.src.options[i].selected) {
                this.target.appendChild(this.src.options[i]);
                i--;
            }
        }
    },

    moreSrc: function(srcURL)
    {
        var page = this.currentpage = this.currentpage + 1;
        var params = 'page=' +  page + '&perpage=' + this.perpage;
        var ajax = new Ajax.Request(srcURL,
                                    {
                                        method: 'get',
                                        parameters: params,
                                        onComplete: this._moreSrcComplete
                                    });
    },

    _moreSrcComplete: function(response)
    {
        alert('success');
        alert(this.currentpage);
    }
});
<?php
            $loaded = true;
        }
?>
// execute as anonymous function to hide variables from the global scoope
(function(){
    var updater = new Sabai_Form_Element_SelectEntities_Updater($('<?php echo $src;?>'), $('<?php echo $target;?>'), <?php echo intval($total);?>, <?php echo intval($perpage);?>);
    Event.observe($('<?php echo $button_src;?>'), 'click', function(){updater.targetToSrc();});
    Event.observe($('<?php echo $button_target;?>'), 'click', function(){updater.srcToTarget();});
    Event.observe($('<?php echo $button_more;?>'), 'click', function(){updater.moreSrc('<?php echo SABAI_URL_DIR;?>/ajax.php/<?php echo pluralize($this->_entityName);?>')});
})();
</script>
<?php
        return ob_get_clean();
    }
}